
window.onload = firstVisit;



function firstVisit() {
    let res = new XMLHttpRequest();
    
    res.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            let table = createTable();

            let json = JSON.parse(this.responseText);

            for (let i = 0; i<json.length; i++) {
                let row = document.createElement("tr");
                for (let e in json[i]) {
                    let item = document.createElement("td");
                    item.innerText = json[i][e];
                    row.appendChild(item);
                }
                table.appendChild(row);
            }

            document.getElementById("searchForm").insertAdjacentElement("afterend", table);
        }
    }
    res.open("post", "http://localhost:8080/visit");

    res.send();

}

function search() {
    let input = document.getElementById("keyword");


    let res = new XMLHttpRequest();
    res.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            let h1 = document.createElement("h1");
            h1.innerText = "Search Result:";

            let table = createTable();

            let row = document.createElement("tr");
            let json = JSON.parse(this.responseText);
            for (let e in json) {
                let item = document.createElement("td");
                item.innerText = json[e];
                row.appendChild(item);
            }
            table.appendChild(row);

            document.getElementById("searchForm").insertAdjacentElement("afterend", table);
            table.insertAdjacentElement("beforebegin", h1);
        }
    }
    res.open("post", "http://localhost:8080/search");
    res.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    res.send("country="+encodeURIComponent(input.value));

}

function createTable() {
    let table = document.createElement("table");

    let head = document.createElement("tr");
    let state = document.createElement("th");
    let country = document.createElement("th");
    let lat = document.createElement("th");
    let lon = document.createElement("th");

    state.innerText = "Province/State";
    country.innerText = "Country/Region";
    lat.innerText = "Lat";
    lon.innerText = "Long";


    head.appendChild(state);
    head.appendChild(country);
    head.appendChild(lat);
    head.appendChild(lon);

    table.appendChild(head);

    return table;
}